package org.example.dao;

import com.github.pagehelper.PageInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * @author yuntao.shen
 * @date 2019/4/15
 */
@Component
@Slf4j
public class DataSourceCreator {

    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, String dbIndex) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources1 = resolver.getResources("classpath:mapper/" + dbIndex + "/*.xml");
            Resource[] resources2 = resolver.getResources("classpath:customMapper/" + dbIndex + "/*.xml");
            Resource[] resources3 = resolver.getResources("classpath:mapper/" + dbIndex + "/*/*.xml");
            Resource[] resources4 = resolver.getResources("classpath:customMapper/" + dbIndex + "/*/*.xml");
            sqlSessionFactory.setMapperLocations(ArrayUtils.addAll(ArrayUtils.addAll(ArrayUtils.addAll(resources1, resources2), resources3), resources4));
        } catch (IOException e) {
            log.error("[DataSourceConfiguration-sqlSessionFactory]读取mapper.xml异常！", e);
            e.printStackTrace();
        }
        sqlSessionFactory.setPlugins(new Interceptor[]{ pageInterceptor() });
        return sqlSessionFactory.getObject();
    }

    @Bean
    public PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "false");
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("pageSizeZero", "true");
        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }

}
